const drugModel = require('../models/Drug');

// 获取所有药品
const getAllDrugs = async (req, res) => {
    try {
        const drugs = await drugModel.getAllDrugs();
        res.json(drugs);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

// 创建新药品
const createDrug = async (req, res) => {
    try {
        const { name, description, price, stock, image, category } = req.body;
        
        // 验证必需字段
        if (!name || !description || price === undefined || stock === undefined || !category) {
            return res.status(400).json({ message: '缺少必需字段' });
        }

        const drugId = await drugModel.createDrug(name, description, price, stock, image || null, category);
        res.status(201).json({ id: drugId });
    } catch (error) {
        console.error('创建药品错误:', error);
        res.status(400).json({ message: error.message });
    }
};

// 根据 ID 获取药品
const getDrugById = async (req, res) => {
    try {
        const { id } = req.params;
        const drug = await drugModel.getDrugById(id);
        if (!drug) {
            return res.status(404).json({ message: 'Drug not found' });
        }
        res.json(drug);
    } catch (error) {
        res.status(500).json({ message: error.message });
    }
};

// 更新药品信息
const updateDrug = async (req, res) => {
    try {
        const { id } = req.params;
        const { name, description, price, stock } = req.body;
        const affectedRows = await drugModel.updateDrugById(id, name, description, price, stock);
        if (affectedRows === 0) {
            return res.status(404).json({ message: 'Drug not found' });
        }
        res.json({ message: 'Drug updated successfully' });
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
};

// 删除药品
const deleteDrug = async (req, res) => {
    try {
        const { id } = req.params;
        const affectedRows = await drugModel.deleteDrugById(id);
        if (affectedRows === 0) {
            return res.status(404).json({ message: 'Drug not found' });
        }
        res.json({ message: 'Drug deleted successfully' });
    } catch (error) {
        res.status(400).json({ message: error.message });
    }
};

module.exports = {
    getAllDrugs,
    createDrug,
    getDrugById,
    updateDrug,
    deleteDrug
};